﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RastinArgham.Website.Models;
using RastinArgham.Website.CRMWCF;
using Mani.Common;
using Microsoft.Web.Helpers;

namespace RastinArgham.Website.Controllers
{
    public class OrderController : Controller
    {

        public static IEnumerable<ContactType> ContactTypes = new List<ContactType> {  
            new ContactType {
                Id = -1,
                Description = "---"
            },
            new ContactType { 
                Id = 1, 
                Description = "حقیقی" 
            }, 
            new ContactType { 
                Id = 2, 
                Description = "حقوقی" 
            } 
        };

        public static IEnumerable<City> GetCities()
        {
            CRMWCF.CRMAPIClient crm = new CRMWCF.CRMAPIClient();
            List<City> cities = new List<City>();
            cities.Add(new City { CityId = -1, CityName = "---" });
            cities.AddRange(crm.GetCities().Select(c => new City { CityId = c.CityId, CityName = c.CityName }).ToList());
            
            return cities;
        }

        public static IEnumerable<Service> GetServices()
        {
            CRMWCF.CRMAPIClient crm = new CRMWCF.CRMAPIClient();
            List<Service> services = new List<Service>();
            services.Add(new Service { Description = "---", ServiceId = -1, Price = 0, ProvinceId = -1, ServiceName = "---", ServicePeriod = 1, TaxPercent = 0 });
            services.AddRange(crm.GetServices().Select( s => new Service { Description = s.Description, Price = s.Price, ProvinceId = s.ProvinceId, ServiceId = s.ServiceId, ServiceName = s.ServiceName, ServicePeriod = s.ServicePeriod, TaxPercent = s.TaxPercent }).ToList());

            return services;
        }

        //
        // GET: /Order/New
        public ActionResult New()
        {
            return View();
        } 

        //
        // POST: /Order/New
        [HttpPost]
        public ActionResult New(OrderViewDTO model)
        {
            LoggingWCF.LoggingAPIClient logger = new LoggingWCF.LoggingAPIClient();

            try
            {
                if (!ReCaptcha.Validate(privateKey: "6LfR58kSAAAAAIZ8CUoptSr-aWhh9FsJuoABF9wz"))
                {
                    ModelState.AddModelError("", "لطفا حروف تصویر امنیتی را مجددا وارد کنید");
                    logger.LogError(Request.Path, String.Format("Captcha validation failed for user! Mobile: {0}, Email: {1}", model.MobilePhone, model.Email), "Captcha validation failed!", Request.UserAgent);
                    return View();
                }

                if (ModelState.IsValid)
                {
                    CRMWCF.CRMAPIClient crm = new CRMWCF.CRMAPIClient();
                    OrderDTO o = new OrderDTO();
                    o.OrderDate = DateTime.Now;
                    o.ServiceId = model.ServiceId.Value;

                    ContactDTO c = new ContactDTO();

                    c.ContactTypeId = model.ContactTypeId;
                    c.AcademicDegree = model.AcademicDegree;
                    c.Address = model.Address;
                    c.Birthday = DateTime.Now.AddYears(-30);

                    c.CityId = model.CityId;
                    c.CompanyActivityField = model.CompanyActivityField;
                    c.CompanyName = model.CompanyName;
                    c.EducationalMajor = model.EducationalMajor;
                    c.Email = model.Email;
                    c.FatherName = model.FatherName;
                    c.Fax = model.Fax;
                    c.FirstName = model.FirstName;
                    c.IdentityIssuePlace = model.IdentityIssuePlace;
                    c.IdentityNumber = model.IdentityNumber;
                    c.Job = model.Job;
                    c.LastName = model.LastName;
                    c.ManagerAcademicDegree = model.ManagerAcademicDegree;
                    c.ManagerBirthday = DateTime.Now.AddYears(-30);
                    c.ManagerEducationalMajor = model.ManagerEducationalMajor;
                    c.ManagerFirstName = model.ManagerFirstName;
                    c.ManagerFullNameEnglish = model.ManagerFullNameEnglish;
                    c.ManagerLastName = model.ManagerLastName;
                    c.ManagerNationalCode = model.ManagerNationalCode;
                    c.MobilePhone = model.MobilePhone;
                    c.NationalCode = model.NationalCode;
                    c.Phone = model.Phone;
                    c.RegistrationNumber = model.RegistrationNumber;
                    c.Website = model.Website;
                    c.ZipCode = model.ZipCode;

                    if (model.ContactTypeId == 1)
                    {
                        c.ContactTitle = model.FirstName + " " + model.LastName;
                        c.FullContactTitle = model.EnglishFullName;
                    }
                    else
                    {
                        c.ContactTitle = model.CompanyName;
                        c.FullContactTitle = model.CompanyEnglishName;
                    }

                    if (Request.Cookies["Campaign"] != null)
                        c.CampaignCode = Request.Cookies["Campaign"].Value;

                    o.Contact = c;
                    int contactId = crm.NewOrder(o);
                    return RedirectToAction("Success/" + contactId.ToString());
                }
                else
                {
                    // Validation failed
                    return View();
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "متاسفانه روند سفارش با خطا روبه رو شده است لطفا مجددا تلاش کنید");
                logger.LogError(Request.Path, String.Format("User New Order failed! Mobile: {0}, Email: {1}", model.MobilePhone, model.Email), ex.ToString(), Request.UserAgent);
                return View();
            }
        }


        //
        // GET: /Order/Success/id
        public ActionResult Success(int id)
        {
            ViewData["ReferenceCode"] = id;
            return View();
        }
    }
}
